package com.smile.frame.websocket.netty.service.handler;

import com.smile.frame.websocket.netty.service.repository.ChannelRepository;
import com.smile.frame.websocket.netty.service.repository.ClientRepository;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 异常处理 handler
 *
 * @author LGC
 * @ChannelHandler.Sharable 保证处理器，在整个生命周期中就是以单例的形式存在
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class ExceptionHandler extends ChannelInboundHandlerAdapter {

    /**
     * 发生异常,断开连接
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel = ctx.channel();
        String channelId = channel.id().asLongText();
        //移除通信过的channel
        ChannelRepository.removeChannel(channelId);
        //移除和用户绑定的channel
        ClientRepository.removeClient(channelId);
        log.error("发生异常断开连接Channel:{},RemoteAddress:{},ThreadName:{}", channelId, channel.remoteAddress(), Thread.currentThread().getName(), cause);
        //关闭长连接
        ctx.close();
    }

    /**
     * 通道 Read 读取 Complete 完成
     * 做刷新操作 ctx.flush()
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();//刷新后才将数据发出到SocketChannel
    }

}